/**
 * 2018/6/29 10:07:30 Wen Jun created.
 */

package com.diver.flinkdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diver.flinkdemo.dto.xxt.StudentCardBindingsDto;
import com.diver.flinkdemo.entity.Trd.ProvincialZhongTai.ProvincialZTUserInfo;
import com.diver.flinkdemo.entity.xxt.User;
import com.diver.flinkdemo.entity.xxt.UserStudentCard;
import com.diver.flinkdemo.mapper.mysqlMapper.PersonTerminalInfoMapper;
import com.diver.flinkdemo.mapper.mysqlMapper.UserStudentCardMapper;
import com.diver.flinkdemo.service.IPersonTerminalInfoService;
import com.diver.flinkdemo.service.IUserService;
import com.diver.flinkdemo.service.IUserStudentCardService;
import com.diver.flinkdemo.utils.DynamicDataSourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 学生-用户中间表 Service 实现
 * Created by Wen Jun on 2018/06/29.
 */
//@Service
@Slf4j
public class UserStudentCardService implements IUserStudentCardService {

//    @Autowired
    private IUserService userService = new UserService();
    private UserStudentCardMapper mapper;
    private SqlSession session;
    private IPersonTerminalInfoService personTerminalInfoService = new IPersonTerminalInfoServiceImpl();

    @Override
    public List<StudentCardBindingsDto> getStudentCardBindings(String studentCardId) {
        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession();
            mapper = session.getMapper(UserStudentCardMapper.class);
            List<StudentCardBindingsDto> studentCardBindingsDtos = new ArrayList<>();
            /*List<StudentCardBindingsDto> studentCardBindingsDtos = new ArrayList<>();
            QueryWrapper<UserStudentCard> wrapper = new QueryWrapper<>();
            wrapper.eq("student_card_id",studentCardId);
            List<UserStudentCard> userStudentCards = mapper.selectList(wrapper);*/
            String personId = personTerminalInfoService.getBindPersonId(studentCardId);
            List<ProvincialZTUserInfo> userStudentCards = getProvincialZTUserInfo(personId);
            if (userStudentCards != null && !userStudentCards.isEmpty()) {
                for (int i = 0; i < userStudentCards.size(); i++) {
                    ProvincialZTUserInfo usc = userStudentCards.get(i);
                    StudentCardBindingsDto scbdto = new StudentCardBindingsDto();
                    scbdto.setCreateTime((Date) usc.getCreateTime());
                    scbdto.setUserName(usc.getNickName());
                    scbdto.setAccountName(usc.getChannelName());
                    studentCardBindingsDtos.add(scbdto);
                }
                return studentCardBindingsDtos;
            }
            return null;
        } finally {
            endOfSession(session);
        }
    }

    @Override
    public List<ProvincialZTUserInfo> getProvincialZTUserInfo(String personId) {
        try {
            session = DynamicDataSourceUtil.mysqlSessionFactory.openSession();
            mapper = session.getMapper(UserStudentCardMapper.class);
            List<ProvincialZTUserInfo> provincialZTUserInfo = mapper.getProvincialZTUserInfo(personId);
            return provincialZTUserInfo;
        } finally {
            endOfSession(session);
        }
    }

//    @Autowired
//    private IUserStudentCardDao userStudentCardDao;
//
//    @Autowired
//    private UserStudentCardMapper userStudentCardMapper;
//    @Autowired
//    protected PropsConfig propsConfig;
//    @Autowired
//    protected StudentCardService cardService;
//    @Autowired
//    protected TrajectoryClient trajectoryClient;
//
//    @Override
//    public IIbatisDataProvider<UserStudentCard, String> getModelDao() {
//        return this.userStudentCardDao;
//    }
//
//    @Override
//    public String bindStudentCard(StudentCard studentCard, UserRedis userRedis, boolean needStrategy) {
//        String studentCardId = studentCard.getId();
//        String userId = userRedis.getUserId();
//        String channel = userRedis.getChannel();
//        //判断是否重复绑定
//        QueryParams params = new QueryParams();
//        params.addParameter("studentCardId", studentCardId);
//        params.addParameter("userId", userId);
//        int count = queryCount(params);
//        logger.debug("bindnum：{}", count);
//        if (count > 0) {
//            return "重复绑定";
//        }
//        UserStudentCard userStudentCard = new UserStudentCard();
//        if (needStrategy) {
//            try {//下发周期策略 & 初始化上学守护信息
//                String initialState = studentCard.getInitialState();
//                if (CommonResource.STU_INITIAL_STATE_NORMAL.equals(initialState)) {
//                    String cardType = studentCard.getCardType();
//                    deliverStrategy(studentCardId, cardType);
//                    if (CommonResource.CHANNEL_TRAJECTORY.equals(channel)) {
//                        trajectoryClient.initGuardTime(studentCard);//初始化上学守护
//                    }
//                }
//            } catch (Exception e) {
//                logger.error("下发周期策略/初始化上学守护 异常:", e);
//            }
//        }
//        long time = System.currentTimeMillis();
//        userStudentCard.setStudentCardId(studentCardId);
//        userStudentCard.setUserId(userId);
//        userStudentCard.setCreateTime(time);
//        userStudentCard.setIsTip(1);
//        doAddModel(userStudentCard);//添加绑定信息
//        changeStudentCard(userId, studentCardId);//设置当前学生证为最近使用
//        //pushBindMsgToCDTelecom(studentCard.getImei(), userRedis.getOpenId(), userRedis.getAccountId(), time);//绑定成功推送绑定信息至电信产创平台
//        return "success";
//    }
//
//    @Override
//    public String bindStudentCardNew(StudentCard studentCard, UserRedis userRedis, boolean needStrategy) {
//        String studentCardId = studentCard.getId();
//        String userId = userRedis.getUserId();
//        String channel = userRedis.getChannel();
//        UserStudentCard userStudentCard = new UserStudentCard();
//        if (needStrategy) {
//            try {//下发周期策略 & 初始化上学守护信息
//                String initialState = studentCard.getInitialState();
//                if (CommonResource.STU_INITIAL_STATE_NORMAL.equals(initialState)) {
//                    String cardType = studentCard.getCardType();
//                    deliverStrategy(studentCardId, cardType);
//                    if (CommonResource.CHANNEL_TRAJECTORY.equals(channel)) {
//                        trajectoryClient.initGuardTime(studentCard);//初始化上学守护
//                    }
//                }
//            } catch (Exception e) {
//                logger.error("下发周期策略/初始化上学守护 异常:", e);
//            }
//        }
//        long time = System.currentTimeMillis();
//        userStudentCard.setStudentCardId(studentCardId);
//        userStudentCard.setUserId(userId);
//        userStudentCard.setCreateTime(time);
//        userStudentCard.setIsTip(1);
//        doAddModel(userStudentCard);//添加绑定信息
//        changeStudentCard(userId, studentCardId);//设置当前学生证为最近使用
//        //pushBindMsgToCDTelecom(studentCard.getImei(), userRedis.getOpenId(), userRedis.getAccountId(), time);//绑定成功推送绑定信息至电信产创平台
//        return "success";
//
//    }
//
//    private void pushBindMsgToCDTelecom(String imei, String platFormUserId, String accountId, Long bindTime) {
//        String channelId = BindChannelEnum.CD_TELECOM.getBindChannel();
//        if (channelId.equals(accountId)) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("userId", platFormUserId);//电信平台用户id
//            map.put("imei", imei);//设备imei
//            map.put("bindTime", bindTime);//绑定时间
//            map.put("channelId", channelId);//渠道号
//            String paramsJson = JSON.toJSONString(map);
//            logger.info("推送绑定信息到成都电信产创平台==>userId：{}，imei：{}", platFormUserId, imei);
//            try {
//                String responst = HttpUrlClient.httpPostWithJSON(propsConfig.getCdtelecomBindmsgUrl(), paramsJson);
//            } catch (Exception e) {
//                logger.error("推送绑定信息异常", e);
//            }
//        }
//    }
//
//    //调用平台接口--下发周期策略
//    @Override
//    public void deliverStrategy(String studentCardId, String cardType) throws Exception {
//        HashMap map = new HashMap();
//        map.put("stuCode", studentCardId);
//        String url = null;
//        if (StuCardTypeEnum.XTN7A.getType().equals(cardType)) {
//            url = propsConfig.getJcApiPrefix() + ApiSuffix.BINDING_STUDENT_CARD;//爱联
//        } else if (StuCardTypeEnum.XTN7B.getType().equals(cardType)) {//成都创利瑞
//            url = propsConfig.getJcApiPrefix() + ApiSuffix.BINDING_STUDENT_CARD_CLR;
//        } else if (StuCardTypeEnum.XTW1.getType().equals(cardType)) {//凌盟
//            url = propsConfig.getJcApiPrefix() + ApiSuffix.BINDING_STUDENT_CARD_LM;
//        } else if (StuCardTypeEnum.XTWB.getType().equals(cardType)) {//手表
//            url = propsConfig.getJcApiPrefix() + ApiSuffix.BINDING_STUDENT_CARD_WB;
//        }
//        if (StringUtils.isNotBlank(url)) {
//            String result = HttpUtils.sendHttpPostJson(url, map);
//            if (StringUtils.isNotBlank(result)) {
//                JSONObject resultJson = JSONObject.parseObject(result);
//                Integer resultCode = resultJson.getInteger("result");
//                if (0 == resultCode) {
//                    logger.info("deliverStrategy success,studentCardId:{}", studentCardId);
//                } else {
//                    String errorMsg = resultJson.getString("errorMsg");
//                    logger.info("deliverStrategy fail:{},studentCardId:{}", errorMsg, studentCardId);
//                }
//            }
//        }
//    }
//
//    @Override
//    public void doUpdateModelByUserIdAndStuId(UserStudentCard userStudentCard) {
//        userStudentCardMapper.doUpdateModelByUserIdAndStuId(userStudentCard);
//    }
//
//    @Override
//    public void changeStudentCard(String userId, String studentCardId) {
//        userStudentCardMapper.changeStudentCard(userId, studentCardId);
//    }
//
//    @Override
//    public List<UserStudentCard> queryBindCardByCardVersion(String userId, List<String> cardTypes) {
//        return userStudentCardMapper.queryBindCardByCardVersion(userId, cardTypes);
//    }
//
//    @Override
//    public void unbindStudentCard(UserStudentCard userStudentCard) {
//        if (null != userStudentCard) {
//            userStudentCardMapper.doDeleteModel(userStudentCard);
//        }
//    }
//
//    @Override
//    public void unbindStudentCardByStudentCardId(String studentCardId) {
//        if (StringUtils.isNotEmpty(studentCardId)){
//            userStudentCardMapper.deleteByStudentCardId(studentCardId);
//        }
//    }
//
//    @Override
//    public List<UserStudentCard> batchUnbindStudentCard(List<String> studentCardIdList) {
//        List<UserStudentCard> list = userStudentCardMapper.getBindsByStudentCardIds(studentCardIdList);
//        if (null != list && !list.isEmpty()) {
//            List<String> cardIdLIst = list.stream().map(UserStudentCard::getStudentCardId).collect(Collectors.toList());
//            userStudentCardMapper.batchDelete(cardIdLIst);
//            return list;
//        }
//        return null;
//    }
//
//    @Override
//    public List<User> getBindUser4LZ(String studentCardId, String accountId) {
//        return userStudentCardMapper.queryBindUserCount(studentCardId, accountId);
//    }
//
//    /**
//     * 获取学生、用户绑定信息
//     * @param userId
//     * @param studentCardId
//     * @return
//     */
//    @Override
//    public UserStudentCard getUserStudentCardByUserAndStudent(String userId ,String studentCardId) {
//        QueryParams params = new QueryParams();
//        params.addParameter("studentCardId", studentCardId);
//        params.addParameter("userId", userId);
//        List<UserStudentCard> studentCards = queryList(params);
//        UserStudentCard userStudentCard = new UserStudentCard();
//        if(studentCards.size() > 0){
//            userStudentCard = studentCards.get(0);
//        }else{
//            userStudentCard.setStudentCardId(studentCardId);
//            userStudentCard.setUserId(userId);
//            userStudentCard.setIsLastUse(1);
//            userStudentCard.setCreateTime(System.currentTimeMillis());
//            userStudentCard = doAddModel(userStudentCard);
//        }
//        return userStudentCard;
//    }
//
//    @Override
//    public List<UserStudentCard> getBindUserStudentCardByStudentCardId(String studentCardId) {
//        return userStudentCardMapper.getBindUserStudentCardByStudentCardId(studentCardId);
//    }
//
//    @Override
//    public void primaryUnbindStudentCard(UserStudentCard userStudentCard) {
//        if (null != userStudentCard) {
//            userStudentCardMapper.doPrimaryDeleteModel(userStudentCard);
//        }
//    }
//    /**
//     * 绑定数据备份
//     */
//    public List<String> bindBackUp(){
//        return userStudentCardMapper.bindBackUp();
//    }

    public void endOfSession(SqlSession session) {
        //关闭sqlSession
        if (session != null) {
            log.info("session commit -> session close");
//            session.commit();
            session.close();
        }
    }
}
